﻿#ifndef NETGAME_H
#define NETGAME_H

#include "board.h"
#include "networkPacket .h"

#include <QTcpSocket>

class NetGame : public Board
{
    Q_OBJECT
public:
    explicit NetGame(QWidget *parent = nullptr);

    void startMatchmaking();
    void sendChessMove(QSharedPointer<Step> step);
    void onDataReceived();

    void processPacket(CommandType cmd, QByteArray data);
    void handleMoveData(QByteArray data);
    void handleMatchSuccessData(QByteArray data);

    bool readHeaderFromSocket(NetworkHeader& header);
    QJsonObject parseJsonObject(const QByteArray& jsonData);
    QJsonArray parseJsonArray(const QByteArray& jsonData);
    void setRoomIdAndOpponentId(QString roomId, QString opponentId);
    void setPlayerSide(bool isRed);

    virtual bool movePiece(int row, int col, int secondId);

    // 悔棋按钮
    QScopedPointer<QPushButton> retrackButton;
    // 局时
    int gameTimeLimitMs;
    // 步时
    int stepTimeLimitMs;
    // 匹配超时时间
    int matchTimeLimitMs;
    // 是否是红方
    bool isRed;
    // 玩家id
    QString playerId;
    QScopedPointer<QTcpSocket> m_socket;
    // 匹配房间id
    QString roomId;
    // 对端玩家id
    QString opponentId;
    // 匹配结果
    MatchResult matchResult;

signals:
    void matchFound(QString roomId, QString opponentId, bool otherIsRed);
    void matchFailed(const QString& reason);
    void moveReceived(QSharedPointer<Step> step);

private slots:
    void onRetrackButtonClicked();
    // 按钮禁用
    void buttonDisable();
    void buttonEnable();
    void handleServerDisconnected();

};

#endif // NETGAME_H
